package com.atguigu.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.ReduceOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author yhm
 * @create 2024-03-30 9:56
 */
public class BatchWordCount {
    public static void main(String[] args) throws Exception {
        // TODO1  构建Flink环境  可以区分创建批处理环境和流处理环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        // TODO2  读取数据源
        DataSource<String> lineDs = env.readTextFile("input/words.txt");

        // TODO3 处理计算
        // 3.1 切分单词
        FlatMapOperator<String, Tuple2<String, Long>> tuple2Op = lineDs.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                // 单词切分
                String[] words = value.split(" ");
                for (String word : words) {
                    // 使用out来完成数据输出
                    out.collect(new Tuple2<>(word, 1L));
                }
            }
        });

        // 3.2 聚合相同单词
        UnsortedGrouping<Tuple2<String, Long>> groupByOp = tuple2Op.groupBy(new KeySelector<Tuple2<String, Long>, String>() {
            @Override
            public String getKey(Tuple2<String, Long> value) throws Exception {
                return value.f0;
            }
        });

        ReduceOperator<Tuple2<String, Long>> resultData = groupByOp.reduce(new ReduceFunction<Tuple2<String, Long>>() {
            // reduce第一个参数是上一次聚合的结果
            // 第二个参数是这一次新加的元素
            // 在第一个reduce计算中  value1就是第一个元素  value2是第二个元素
            @Override
            public Tuple2<String, Long> reduce(Tuple2<String, Long> value1, Tuple2<String, Long> value2) throws Exception {
                return new Tuple2<>(value1.f0, value1.f1 + value2.f1);
            }
        });

        resultData.print();
    }
}
